package com.dacd.pdf.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dacd.pdf.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import ja.burhanrashid52.photoeditor.OnSaveBitmap;
import ja.burhanrashid52.photoeditor.PhotoEditor;
import ja.burhanrashid52.photoeditor.PhotoEditorView;
import me.panpf.sketch.SketchImageView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int CODE_REQUEST_PERMISSION = 0x10;
    private static final String FILENAME = "sample20190115.pdf";//测试用的pdf文件

    private ParcelFileDescriptor mFileDescriptor;// File descriptor of the PDF.
    private PdfRenderer mPdfRenderer;
    private PdfRenderer.Page mCurrentPage;//Page that is currently shown on the screen.
    private PhotoEditor mPhotoEditor;
    private PhotoEditorView pdfShowIv;//显示PDF的区域
    private ImageButton previousBtn;//前一页PDF
    private ImageButton nextBtn;//后一页PDF
    private ImageButton clearBtn;//清除按钮
    private ImageButton linkBtn;//跳转网站按钮
    private ImageButton saveBtn;//保存按钮
    private ImageButton firstPage;//第一页
    private ImageButton lastPage;//最后一页
    private ImageButton movieBtn;//跳转视频链接
    private ImageButton backBtn;//后退按钮
    private int currentIndex;
    private ProgressDialog pDialog;
    private Bitmap currentBitmap;//当前图片的bitmap
    private SketchImageView sketchImageView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getPermission();
        currentIndex = 0;
        initView();
        initImageEditor();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        pdfShowIv = (PhotoEditorView) findViewById(R.id.am_pdf_image);
        sketchImageView = (SketchImageView) findViewById(R.id.am_pdf_zoom_iv);
        pdfShowIv.getSource().setScaleType(ImageView.ScaleType.FIT_CENTER);
        previousBtn = (ImageButton) findViewById(R.id.am_previous_btn);
        nextBtn = (ImageButton) findViewById(R.id.am_next_btn);
        clearBtn = (ImageButton) findViewById(R.id.am_init_btn);
        linkBtn = (ImageButton) findViewById(R.id.am_link_btn);
        saveBtn = (ImageButton) findViewById(R.id.am_save_btn);
        firstPage = (ImageButton) findViewById(R.id.am_first_page_btn);
        lastPage = (ImageButton) findViewById(R.id.am_latest_page_btn);
        movieBtn = (ImageButton) findViewById(R.id.am_movie_btn);
        backBtn = (ImageButton) findViewById(R.id.am_back_btn);
        previousBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        clearBtn.setOnClickListener(this);
        linkBtn.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        firstPage.setOnClickListener(this);
        lastPage.setOnClickListener(this);
        movieBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
    }

    /**
     * 初始化图片编辑器
     */
    private void initImageEditor() {
        mPhotoEditor = new PhotoEditor.Builder((Context) this, pdfShowIv)
                .setPinchTextScalable(false)
                .build();
        mPhotoEditor.setBrushDrawingMode(true);
        mPhotoEditor.setBrushSize(10);
        mPhotoEditor.setBrushColor(Color.BLACK);
    }

    @Override
    protected void onStart() {
        super.onStart();
        openPdf();
    }

    /**
     * Sets up a {@link android.graphics.pdf.PdfRenderer} and related resources.
     */
    private void openRenderer(Context context) throws IOException {
        // In this sample, we read a PDF from the assets directory.
        File file = new File(context.getCacheDir(), FILENAME);
        if (!file.exists()) {
            // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
            // the cache directory.
            InputStream asset = context.getAssets().open(FILENAME);
            FileOutputStream output = new FileOutputStream(file);
            final byte[] buffer = new byte[1024];
            int size;
            while ((size = asset.read(buffer)) != -1) {
                output.write(buffer, 0, size);
            }
            asset.close();
            output.close();
        }
        mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        // This is the PdfRenderer we use to render the PDF.
        if (mFileDescriptor != null) {
            mPdfRenderer = new PdfRenderer(mFileDescriptor);
        }
    }

    /**
     * Shows the specified page of PDF to the screen.
     *
     * @param index The page index.
     */
    private void showPage(int index) {
        if (mPdfRenderer.getPageCount() <= index) {
            return;
        }
        // Make sure to close the current page before opening another one.
        if (null != mCurrentPage) {
            try {
                mCurrentPage.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // Use `openPage` to open a specific page in PDF.
        mCurrentPage = mPdfRenderer.openPage(index);
        // Important: the destination bitmap must be ARGB (not RGB).
        currentBitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
                Bitmap.Config.ARGB_8888);
        RelativeLayout.LayoutParams imgSrcParam = new RelativeLayout.LayoutParams(
                mCurrentPage.getWidth(), mCurrentPage.getHeight());
        imgSrcParam.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        pdfShowIv.setLayoutParams(imgSrcParam);
        // Here, we render the page onto the Bitmap.
        // To render a portion of the page, use the second and third parameter. Pass nulls to get
        // the default result.
        // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
        mCurrentPage.render(currentBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        // We are ready to show the Bitmap to user.
        pdfShowIv.getSource().setImageBitmap(currentBitmap);
        updateUi();
    }

    /**
     * Updates the state of 2 control buttons in response to the current page index.
     */
    private void updateUi() {
        currentIndex = mCurrentPage.getIndex();
        int pageCount = mPdfRenderer.getPageCount();
        previousBtn.setEnabled(0 != currentIndex);
        nextBtn.setEnabled(currentIndex + 1 < pageCount);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.am_previous_btn: {
//                // Move to the previous page
                showPage(mCurrentPage.getIndex() - 1);
                mPhotoEditor.clearAllViews();
                break;
            }
            case R.id.am_next_btn: {
//                pdfShowIv.setVisibility(View.GONE);
//                sketchImageView.setImageBitmap(currentBitmap);
//                sketchImageView.setZoomEnabled(true);
//                sketchImageView.setVisibility(View.VISIBLE);
                // Move to the next page
                showPage(mCurrentPage.getIndex() + 1);
                mPhotoEditor.clearAllViews();
                break;

            }
            case R.id.am_init_btn: {
                mPhotoEditor.clearAllViews();
                break;
            }
            case R.id.am_link_btn: {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("https://www.sinwanet.co.jp/");
                intent.setData(content_url);
                startActivity(intent);
                break;
            }
            case R.id.am_save_btn: {
                if (getPermission()) {//如果有SD卡的许可才能进行操作
                    pDialog = ProgressDialog.show(this, ""
                            , getString(R.string.common_loading), false, false);
                    saveAsPdfFile();
                }
                break;
            }
            case R.id.am_first_page_btn: {
                showPage(0);
                mPhotoEditor.clearAllViews();
                break;
            }
            case R.id.am_latest_page_btn: {
                showPage(mPdfRenderer.getPageCount() - 1);
                mPhotoEditor.clearAllViews();
                break;
            }
            case R.id.am_movie_btn: {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("https://youtu.be/yZbnUQPr38Y");
                intent.setData(content_url);
                startActivity(intent);
                break;
            }
            case R.id.am_back_btn:{
                finish();
                break;
            }
        }
    }

    private void saveAsPdfFile() {
//        String sdPath = FileUtils.getSDPath();
//        if (sdPath == null) {//没有SD卡不能保存，可以添加提示
//            return;
//        }
        checkSdFolder();
    }

    @SuppressLint("MissingPermission")
    private void checkSdFolder() {
        mPhotoEditor.saveAsBitmap(new OnSaveBitmap() {
            @Override
            public void onBitmapReady(Bitmap saveBitmap) {
                saveAsPdf(saveBitmap);
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    private void saveAsPdf(Bitmap saveBitmap) {
        // create a new document
        PdfDocument document = new PdfDocument();
        if (null != mCurrentPage) {
            mCurrentPage.close();
        }
        // crate a page description
        for (int i = 0; i < mPdfRenderer.getPageCount(); i++) {
            if (i == currentIndex) {
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(saveBitmap.getWidth()
                        , saveBitmap.getHeight(), 0).create();
                createPdfPage(document, pageInfo, saveBitmap);
            } else {
                mCurrentPage = mPdfRenderer.openPage(i);
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(mCurrentPage.getWidth()
                        , mCurrentPage.getHeight(), 0).create();
                Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
                        Bitmap.Config.ARGB_8888);
                // Here, we render the page onto the Bitmap.
                // To render a portion of the page, use the second and third parameter. Pass nulls to get
                // the default result.
                // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
                mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                if (null != mCurrentPage) {
                    mCurrentPage.close();
                }
                createPdfPage(document, pageInfo, bitmap);
            }
        }
        // 输出到文件
        try {
            File file = new File(getCacheDir(), FILENAME);
            FileOutputStream outputStream = new FileOutputStream(file);
            document.writeTo(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        openPdf();
        if (pDialog != null) {
            pDialog.cancel();
        }
        new AlertDialog.Builder(this)
                .setMessage(R.string.am_commit_success)
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton(R.string.common_ok_jp, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                })
                .create().show();
    }

    private void openPdf() {
        try {
            openRenderer(this);
            showPage(currentIndex);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void createPdfPage(PdfDocument document, PdfDocument.PageInfo pageInfo, Bitmap saveBitmap) {
        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);
        Canvas canvas = page.getCanvas();
        Paint mPaint = new Paint();
        canvas.drawBitmap(saveBitmap, 0, 0, mPaint);
        document.finishPage(page);
    }

    /**
     * 获取权限
     *
     * @return
     */
    private boolean getPermission() {
        int hasWriteStoragePermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_REQUEST_PERMISSION);
            return false;
        }
        return true;
    }
}
